package com.testapp.bluetoothtest08.Home;


import androidx.fragment.app.Fragment;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.testapp.bluetoothtest08.Constant.Constants;
import com.testapp.bluetoothtest08.File.ChallengeFile;
import com.testapp.bluetoothtest08.File.Cipher;
import com.testapp.bluetoothtest08.File.GenerateKeyFile;
import com.testapp.bluetoothtest08.File.ScanCodeFirstRequestFile;
import com.testapp.bluetoothtest08.File.ScanCodeSecondRequestFile;
import com.testapp.bluetoothtest08.File.ScanMachineFile;
import com.testapp.bluetoothtest08.File.Statement;
import com.testapp.bluetoothtest08.File.Token;
import com.testapp.bluetoothtest08.File.UserScanCodeDataFile;
import com.testapp.bluetoothtest08.Http.OkHttp;
import com.testapp.bluetoothtest08.Judge.IsYellow;
import com.testapp.bluetoothtest08.R;
import com.testapp.bluetoothtest08.Util.RequestCodeGenerateUtil;
import com.testapp.bluetoothtest08.cipher.UserCipherService;
import com.testapp.bluetoothtest08.cipher.entity.ScanCodeFirstRequest;
import com.testapp.bluetoothtest08.cipher.entity.ScanCodeSecondRequest;
import com.testapp.bluetoothtest08.cipher.entity.user.UserPrivateData;
import com.testapp.bluetoothtest08.cipher.entity.user.UserPrivateDataStr;
import com.testapp.bluetoothtest08.cipher.entity.user.UserScanCodeData;
import com.testapp.bluetoothtest08.cipher.impl.UserCipherServiceImpl;
import com.testapp.bluetoothtest08.pojo.QRCodeEntity;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HomeFragment extends Fragment {

    private ImageView QRCode;
    private View v;
    private AMapLocationClient mClient;
    private TextView time;
    private Button send;
    private static String location;
    private static double latitude;
    private static double longitude;
    private String cipher;
    private String key;
    OkHttp okHttp = new OkHttp();
    UserCipherService userCipherService = new UserCipherServiceImpl();

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (v == null) {
            v = inflater.inflate(R.layout.activity_home_fragment, container, false);
        }
        QRCode = v.findViewById(R.id.qrCode);
        time = v.findViewById(R.id.home_time);
//        send = v.findViewById(R.id.Send);
//        send.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                send();
//            }
//        });
        startLocation();
        return v;
    }


    // ------ 定位操作

    private final AMapLocationListener mListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            System.out.println("进入 二维码生成");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date(System.currentTimeMillis());
            // ---------------------- 先跑一遍定时 --------------------
            new RequestCodeGenerateUtil().requestUpdate();
            // ---------------------- 先跑一遍定时 --------------------

            //判断是否生成
            key = new GenerateKeyFile().read();
            String c = new ChallengeFile().read();
            String f = new ScanCodeFirstRequestFile().read();
            String s = new ScanCodeSecondRequestFile().read();
            String u = new UserScanCodeDataFile().read();
//            System.out.println("data --> " +c+f+s+u);
            if ((key == null || key.equals("")) ||
                    (c == null || c.equals("")) ||
                    (f == null || f.equals("")) ||
                    (s == null || s.equals("")) ||
                    (u == null || u.equals(""))
            ) {
                generate(aMapLocation, simpleDateFormat, date);
            } else {
                generateWithLocalData(aMapLocation, simpleDateFormat, date);
            }
            //通过key生成二维码
            key = new GenerateKeyFile().read();
            System.out.println("key --- >" + key);
            String state = new Statement().read();
            if (state.equals("正常者")) {
                QRCode.setImageBitmap(encodeAs(key, Color.parseColor("#698B22")));
            } else if (state.equals("确诊者")||state.equals("违规者")) {
                QRCode.setImageBitmap(encodeAs(key, Color.RED));
            } else if (state.equals("接触者")) {
                QRCode.setImageBitmap(encodeAs(key, Color.parseColor("#CD853F")));
            } else {
                QRCode.setImageBitmap(encodeAs(key, Color.BLACK));
            }
            if(state.equals("违规者")){
                time.setText("你已违规");
            }else{
                time.setText("更新时间:" + simpleDateFormat.format(date));
            }

//            send();
        }

    };
//#698B22
    private void send (){
        new Thread(new Runnable() {
            @Override
            public void run() {
                String URL = "/trail/scan";
                String data = new GenerateKeyFile().read();
                System.out.println("扫码发送KEY --"+data);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("key", data);
                jsonObject.put("scannerId", 1);
                System.out.println("扫码机发送 ---> " + jsonObject.toJSONString());
                if (data != null) {
                    String r = okHttp.httpPost(URL, jsonObject.toJSONString());
                    System.out.println("扫码后 返回" + r);
                }
            }
        }).start();
    }
    private void startLocation() {
        //创建实例
        try {
            mClient = new AMapLocationClient(this.getContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //绑定监听器
        mClient.setLocationListener(mListener);
        //设定选项
        AMapLocationClientOption option = new AMapLocationClientOption();
        //设定高精度
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设定为是否需要获取地址信息
        option.setNeedAddress(true);
        //设定刷新周期
        option.setInterval(1000 * 60);
        //允许使用模拟定位
        option.setMockEnable(true);
        mClient.setLocationOption(option);

        //重启定位
        mClient.stopLocation();
        mClient.startLocation();
    }

    private void stopLocation() {
        mClient.stopLocation();
        mClient.onDestroy();
    }
    // ------ 定位操作结束

    @Override
    public void onDestroy() {
        stopLocation();
        super.onDestroy();
    }
    // ------> 二维码 <--------


    public Bitmap encodeAs(String str, int color) {
        if (str == null) {
            str = "null";
        }
        Bitmap bitmap = null;
        BitMatrix result = null;
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        try {
            Map<EncodeHintType, String> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            result = multiFormatWriter.encode(str, BarcodeFormat.QR_CODE, 250, 250, hints);
            result = deleteWhite(result);
            // 使用 ZXing Android Embedded 要写的代码
            //BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
            bitmap = createBitmap(result, color);
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException iae) {
            return null;
        }
        return bitmap;
    }


    private static BitMatrix deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1]))
                    resMatrix.set(i, j);
            }
        }
        return resMatrix;
    }

    public Bitmap createBitmap(BitMatrix matrix, int color) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            int offset = y * width;
            for (int x = 0; x < width; x++) {
                pixels[offset + x] = matrix.get(x, y) ? color : Color.WHITE;
            }
        }

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }

    public void generate(AMapLocation aMapLocation, SimpleDateFormat simpleDateFormat, Date date) {
        System.out.println("进入 生成数据....");
        QRCodeEntity qrCodeEntity = new QRCodeEntity();

        location = aMapLocation.getAddress();
        latitude = aMapLocation.getLatitude();
        longitude = aMapLocation.getLongitude();


        String challenge = String.valueOf(System.currentTimeMillis());
        //第一阶段的密码
        cipher = new Cipher().read();
        UserPrivateDataStr cipherUPDS = JSONObject.parseObject(cipher, UserPrivateDataStr.class);
        //转换成 UserPrivateData
        UserPrivateData upd = new UserPrivateData(cipherUPDS);

        //获取三个参数
        List<Object> list = userCipherService.scanCodeRequestCombine(upd, challenge);
        UserScanCodeData uscd = (UserScanCodeData) list.get(0);
        ScanCodeFirstRequest scfr = (ScanCodeFirstRequest) list.get(1);
        ScanCodeSecondRequest scsr = (ScanCodeSecondRequest) list.get(2);
        //写入
        String data = JSONObject.toJSONString(uscd);
        String first = JSONObject.toJSONString(scfr);
        String second = JSONObject.toJSONString(scsr);
        new UserScanCodeDataFile().write(data);
        new ScanCodeFirstRequestFile().write(first);
        new ScanCodeSecondRequestFile().write(second);
        new ChallengeFile().write(challenge);


        //scfr和scsr丢入实体
        qrCodeEntity.setLocation(location);
        qrCodeEntity.setLatitude(String.valueOf(latitude));
        qrCodeEntity.setLongitude(String.valueOf(longitude));
        qrCodeEntity.setQrCodeCreateTime(simpleDateFormat.format(date));
        qrCodeEntity.setChallenge(challenge);
        qrCodeEntity.setScanCodeFirstRequest(scfr);
        qrCodeEntity.setScanCodeSecondRequest(scsr);
        qrCodeEntity.setToken(new Token().read());
        qrCodeEntity.setKey(new GenerateKeyFile().read());
        if(latitude!=0&&longitude!=0){
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    //转为json发送给服务器
                    System.out.println("进入 请求key");
                    System.out.println();
                    String str = JSONObject.toJSONString(qrCodeEntity);
                    System.out.println("二维码数据 ----> " + str);
                    //服务器接收
                    String result = okHttp.httpPost(Constants.QR_SEND_URL, str);
                    System.out.println("发送二维码数据 ---> 服务器返回 ---->" + result);
                    JSONObject D = JSONObject.parseObject(result);
                    if (D != null) {
                        key = D.getString("data");
                        System.out.println("key --- >" + key);
                        //写入参数-----------------
                        if (key != null) {
                            new GenerateKeyFile().write(key);
                        }
                        if(D.getIntValue("code")==-3){
                            new Statement().write("违规者");
                        }

                        //-----------------------
                    }
                }
            });
            thread.start();
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


    }

    public void generateWithLocalData(AMapLocation aMapLocation, SimpleDateFormat simpleDateFormat, Date date) {
        System.out.println("进入 本地数据....");
        QRCodeEntity qrCodeEntity = new QRCodeEntity();
        location = aMapLocation.getAddress();
        latitude = aMapLocation.getLatitude();
        longitude = aMapLocation.getLongitude();

        //第一阶段的密码
        cipher = new Cipher().read();
        UserPrivateDataStr cipherUPDS = JSONObject.parseObject(cipher, UserPrivateDataStr.class);
        //转换成 UserPrivateData
        UserPrivateData upd = new UserPrivateData(cipherUPDS);

        String first = new ScanCodeFirstRequestFile().read();
        ScanCodeFirstRequest scfr = JSONObject.parseObject(first, ScanCodeFirstRequest.class);
        String second = new ScanCodeSecondRequestFile().read();
        ScanCodeSecondRequest scsr = JSONObject.parseObject(second, ScanCodeSecondRequest.class);

        qrCodeEntity.setLocation(location);
        qrCodeEntity.setLatitude(String.valueOf(latitude));
        qrCodeEntity.setLongitude(String.valueOf(longitude));
        qrCodeEntity.setQrCodeCreateTime(simpleDateFormat.format(date));
        qrCodeEntity.setChallenge(new ChallengeFile().read());
        qrCodeEntity.setScanCodeFirstRequest(scfr);
        qrCodeEntity.setScanCodeSecondRequest(scsr);
        qrCodeEntity.setToken(new Token().read());
        qrCodeEntity.setKey(new GenerateKeyFile().read());
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                //转为json发送给服务器
                System.out.println("进入 请求key");
                System.out.println();
                String str = JSONObject.toJSONString(qrCodeEntity);
                System.out.println("二维码数据 ----> " + str);
                //服务器接收
                String result = okHttp.httpPost(Constants.QR_SEND_URL, str);
                System.out.println("发送二维码数据 ---> 服务器返回 ---->" + result);
                JSONObject D = JSONObject.parseObject(result);
                if (D != null) {
                    key = D.getString("data");
                    System.out.println("key --- >" + key);
                    //写入参数-----------------
                    if (key != null) {
                        new GenerateKeyFile().write(key);
                    }
                    if(D.getIntValue("code")==-3){
                        new Statement().write("违规者");
                    }
                    //-----------------------
                }
            }
        });
        thread.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }


}
